import re;
import time,pathlib,os,sys;

SUCCESS = "YES"
FAIL="NO"

logFile = None

def logToFile(*vals):
    print(*vals,file=logFile)

def writeToErr(msg):
    sys.stderr.write(msg+"\n");

def doOutPut(msg):
    logToFile(msg)
    writeToErr(msg)

def checkItemListDispose(fileName:str,content:str=None)->bool:
    # doOutPut("开始检查="+os.path.split(fileName)[1])
    if not content:
        with open(fileName,"r",encoding="utf8") as f:
            content = f.read();
    # pattern = re.compile(r"private\s+?[a-zA-Z0-9]+?\:{1}\s*ItemList",re.DOTALL); #找到私有列表
    # privateItemList = pattern.findall(content)
    # print("privateItemList=",privateItemList)

    # pattern = re.compile(r"private\s+?[a-zA-Z0-9]+?\:{1}\s*ItemList",re.DOTALL|re.MULTILINE);
    # matcher = pattern.match(content); #从字符串开始位置开始匹配

    # pattern = re.compile(r"private\s+?([a-zA-Z0-9]+)?\:{1}\s*ItemList",re.DOTALL|re.MULTILINE);
    # matcher = pattern.search(content); #全文搜索直到找到匹配的项才停止

    pattern = re.compile(r" *?[a-zA-Z]+\s+?dispose\(\)\:.*\{.*\}",re.DOTALL);
    disposeFun = pattern.findall(content);
    # totalVars = getVars(content);#私有变量
    # totalVars.extend(getVars(content,"protected")) 
    # totalVars.extend(getVars(content,"public"))
    # totalVars.extend(getVars(content,""));
    totalVars = getVars(content,"")
    if (not disposeFun or len(disposeFun)==0) and len(totalVars)>0:
        fn = os.path.split(fileName)
        msg = "{0}中存在多个ItemList但是没有执行dispose".format(fn[1])
        doOutPut(msg)
        return
    return checkDisposeFun(fileName,disposeFun,totalVars);

def getVars(content:str,pt:str="private"):
    # pattern = re.compile(pt+r"\s+?[a-zA-Z0-9]+?\:{1}\s*ItemList",re.DOTALL); 
    pattern = re.compile(pt+r"\s+?([_a-zA-Z0-9\-]+)?\:{1}\s*ItemList",re.DOTALL); 
    itemVars = pattern.findall(content)
    return itemVars

def checkDisposeFun(fileName,disposeFun,itemListVarNames)->bool:
    # pattern = re.compile(r"([_a-zA-Z0-9\-]+)?\:{1}\s*ItemList");
    flag = False
    for i in disposeFun: 
        for v in itemListVarNames:
            funcStr:str = i;
            # matcher = pattern.search(v)
            # if not matcher:
            #     continue
            # varName = matcher.groups()[0]
            varName = v.strip()
            logToFile("varName=",varName)
            vn = varName+".dispose()"
            idx = funcStr.find(vn)
            if idx <0:
                fn = os.path.split(fileName)
                msg = "{0}中的{1}没有执行dispose".format(fn[1],v)
                doOutPut(msg)
                if not flag:
                    flag = True
    return flag

def writeContent(svnFile):
    logToFile("\n","writeContent file=",svnFile)
    isFail = False
    try:
        f = open(svnFile,"r")
        changeFiles = f.readlines();
        logToFile("changeFiles=",changeFiles)
        f.close()
        tsFiles = [f.strip() for f in changeFiles if os.path.splitext(f.strip())[1]==".ts"]
        logToFile("tsFiles=",tsFiles)
        if tsFiles and len(tsFiles)>0:
            for f in tsFiles:
                fail = checkItemListDispose(f);
                if not isFail and fail:
                    isFail = fail;
     
    except Exception as e:
        logToFile("\n","writeContent Exception e=",e)
    if isFail:
        return FAIL
    return SUCCESS

if __name__=="__main__":
    selfPath = sys.argv[0]
    rootTuple= os.path.split(selfPath)
    root = rootTuple[0]
    logFile = open(os.path.join(root,"checkLog.txt"),"w+",encoding="utf8")
    count = len(sys.argv);
    retCode = SUCCESS
    logToFile("参数个数=",count)
    if count >1:
        changeFile = sys.argv[1]
        if os.path.isfile(changeFile):
            code = writeContent(changeFile)
            if retCode!=code and code==FAIL:
                retCode = code

    logToFile("retCode=",retCode)
    sys.stdout.write(retCode)
    logFile.close();